package com.wfs.suanfa.nio.xiaoliu.nio1;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class DatagramChannelClientDemo {
    public static void main(String[] args) {
         // 打开DatagramChannel
        DatagramChannel connChannel = null;
        try {
            connChannel = DatagramChannel.open();
            connChannel.bind(new InetSocketAddress(9999));
            // 连接
            connChannel.connect(new InetSocketAddress("127.0.0.1", 9090));
            // write方法
            connChannel.write(ByteBuffer.wrap(String.format("test connect:%s", System.currentTimeMillis())
                    .getBytes(StandardCharsets.UTF_8)));
            // buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);

            while (true) {
                buffer.clear();
                connChannel.read(buffer);
                buffer.flip();
                System.out.println(Charset.forName("UTF-8").decode(buffer));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
